package com.atguigu.com.gulimallouth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.com.gulimallouth.constant.SmsConstant;
import com.atguigu.com.gulimallouth.feign.MemberFeign;
import com.atguigu.com.gulimallouth.vo.LoginVo;
import com.atguigu.com.gulimallouth.vo.RegisterVo;
import com.atguigu.common.constan.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeign memberFeign;


    /**
     * 注册 RedirectAttributes redirectAttributes重定向携带数据
     * @param vo
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/regist")
    public String reg(@Valid RegisterVo vo, BindingResult result,
                      RedirectAttributes redirectAttributes,
                      HttpSession session){
        //检验前台传过来的参数
        if (result.hasErrors()){
            //校验错误
            Map<String,String> map = new HashMap<>();
            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //model.addAttribute("errors",collect);
            redirectAttributes.addFlashAttribute("errors",collect);
            return "redirect:http://outh.gulimall.com/reg.html";
        }else {
            //执行保存操作
            //1.1校验验证码是否正确
            String s = redisTemplate.opsForValue().get(SmsConstant.SMS_PHONE + vo.getPhone());
            String code = s.split("_")[0];
            if (code.equals(vo.getCode())){
                //删除redis中的验证码
                redisTemplate.delete(SmsConstant.SMS_PHONE + vo.getPhone());
                //调用远程服务进行注册
                R register = memberFeign.register(vo);
                if (register.getcode()==0){
                    //成功 放入springSession中
                    MemberVo member = register.getData("member", new TypeReference<MemberVo>() {
                    });
                    session.setAttribute(AuthServerConstant.LOGIN_USER,member);
                    return "redirect:http://gulimall.com";
                }else {
                    //失败
                    String data = register.getData(new TypeReference<String>() {
                    });
                    Map<String,String> map = new HashMap<>();
                    map.put("errors",data);
                    //model.addAttribute("msg",map);
                    redirectAttributes.addFlashAttribute("msg",map);
                    return "redirect:http://outh.gulimall.com/reg.html";
                }
            }else {
                redirectAttributes.addFlashAttribute("errors","验证码不正确！");
                return "redirect:http://outh.gulimall.com/reg.html";
            }
        }
    }

    /**
     * 登陆
     * @param vo
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/login/user")
    public String login( LoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //调用远程登录
//        String string = JSON.toJSONString(vo);
//        LoginVo loginVo = JSON.parseObject(string, LoginVo.class);
        R login = memberFeign.login(vo);
        if(login.getcode()==0){
            //成功
            MemberVo member = login.getData("member", new TypeReference<MemberVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,member);
            return "redirect:http://gulimall.com";
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
